package com.odm.communitymanage.ui.repair

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RadioButton
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.*
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.util.GlideUtils
import com.odm.communitymanage.util.Utils
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.fragment_submit_repair.*


/**
 * @description: 提交维修请求 页面
 * @author: ODM
 * @date: 2020/4/14
 */
class SubmitRepairFragment : BaseMVVMFragment (){

    private var rvAdapter : SubmitRepairAdapter ?= null

    private var viewModel: SubmitRepairViewModel ?= null


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProviders.of(this).get(SubmitRepairViewModel::class.java)
        return super.onCreateView(inflater, container, savedInstanceState)
    }


    override fun initViewModelObserve() {
        /**
         * 判断 提交信息的callback，交互
         */
        viewModel?.postCallBack?.observe(this , Observer{
            if(it.code != 1){
                ToastUtils.showShort(it.message)
            }else {
                //上传成功
                ToastUtils.showShort(StringUtils.getString(R.string.post_success))
                //返回上一页
                pop()
            }
        })
    }

    override fun initViews() {
        ivBack_SubmitRepair.setOnClickListener {
            pop()
        }
        btnSubmitRepair.setOnClickListener {
            //提交编辑的信息
            if(viewModel?.selectedType == -1){
                ToastUtils.showShort("请选择报修的类型")
                return@setOnClickListener
            }
            val desc = etContent_SubmitRepair?.text.toString()
            val phone = etPhoneNumber_SubmitRepair?.text.toString()
            val name = etContactName_SubmitRepair?.text.toString()
            val type = viewModel?.repairTypeList?.get(viewModel?.selectedType ?: 4)?.repairType
            viewModel?.submitRepairData(desc,type,name,phone,viewModel?.photosUris)
        }
        btnSubmitRepairPhoto.setOnClickListener {
            //跳转页面选择图片，当选择了图片后，依次让iv1,iv2,iv3 设为Visible，iv3也可见后将添加图片按钮设为inVisible！
            Utils.openMatissePage(this)
        }

        initSubmitTypeView()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_submit_repair
    }

    /**
     * 初始化提交报修类型的单选列表
     */
    private fun initSubmitTypeView(){
        rvType_SubmitRepair.layoutManager = LinearLayoutManager(requireContext())
        rvAdapter = viewModel?.repairTypeList?.let {
             SubmitRepairAdapter(it)
        }
        rvType_SubmitRepair.adapter  = rvAdapter
        //设置空布局
        rvAdapter?.setEmptyView(R.layout.layout_empty_list)
        //报修列表的item点击事件，选择策略：每一项都与其他项互斥
        rvAdapter?.setOnItemClickListener { adapter, view, position ->
            //将此项设为被选择项，其他项设为不选择
            rvAdapter?.data?.get(position)?.isSelected = true
            if(viewModel?.selectedType != -1){
                //已存在被选的单项，取消它的选中状态, 重置记录的状态
                val selected : RadioButton?= view.findViewById(R.id.checkbox_health_option) as RadioButton
                selected?.isChecked  = false
                rvAdapter?.data?.get(viewModel?.selectedType ?: 0)?.isSelected = false
                viewModel?.selectedType = -1
            }
            val toSelect : RadioButton?= view.findViewById(R.id.checkbox_health_option) as RadioButton
            toSelect?.isChecked = true
            //修改当前被选择 的 体温
            viewModel?.selectedType = position
            rvAdapter?.notifyDataSetChanged()
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //加载从 图库中选择的图片，每次为多张或单张，最多放入3张
        if (requestCode == Constants.REQUEST_IMAGE_CODE && data != null) {
            val result = Matisse.obtainResult(data)
            val uriList: MutableList<Uri> ? = result
            uriList?.let {
                for (uri in uriList) {

                    var target : ImageView  ?= null
                    if (ivSubmitRepairPhoto_1.visibility != View.VISIBLE) {
                        target  = ivSubmitRepairPhoto_1
                    } else if (ivSubmitRepairPhoto_2.visibility != View.VISIBLE) {
                        target  = ivSubmitRepairPhoto_2
                    } else if (ivSubmitRepairPhoto_3.visibility != View.VISIBLE) {
                        target  = ivSubmitRepairPhoto_3
                        btnSubmitRepairPhoto.visibility = View.INVISIBLE
                    }
                    target?.let {
                        GlideUtils.getInstance()
                            .loadImageUri(requireContext(), uri, target)
                        target.visibility = View.VISIBLE
                        //将 图片 Uri 保存起来
                        viewModel?.photosUris?.add(uri)
                    }

                }
            }
        }
    }



}